package com.hqyj.onlineExamination.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器
@Component
public class RequestViewMappingInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory
            .getLogger(RequestViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.debug("==== Pre Interceptor ====");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.debug("==== Post Interceptor ====");

        // 接口（数据）、重定向、转发 无需处理
        if (modelAndView == null ||
                modelAndView.getViewName().toLowerCase().startsWith("redirect") ||
                modelAndView.getViewName().toLowerCase().startsWith("forward")) {
            return;
        }

        //获取请求的path路径，比如/test/thymeleafIndex
        String path = request.getServletPath();
        //打印当前请求的path路径
        LOGGER.debug(request.getServletPath() + "======" + request.getRequestURI());

        //获取当前的template
        String template = (String) modelAndView.getModelMap().getAttribute("template");
        //如果没有手动设置template，并且path不为空
        if (StringUtils.isBlank(template) && StringUtils.isNotBlank(path)) {
            //去掉path前的斜杠
            if (path.startsWith("/")){
                path = path.substring(1, path.length());
            }
            //将path路径设置到template中去
            modelAndView.getModelMap().addAttribute("template", path);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.debug("==== After Interceptor ====");
    }
}
